Módulo 2: Trabalhando com dados
Carolina Musso
PROFESP, DEMSP, MS
O pacote lubridate
As funções if(), if_else() e case_when()
Finalizando noções sobre o pacote flextable()
As estruturas if e else servem para executarmos um código apenas se uma condição (teste lógico) for satisfeita.
A estrutura geral de um if statement é como a seguir:
dados_debola %>%
mutate(Port_Hospital = ifelse(hospital == "Port Hospital", "Sim", "Não")) %>%
select(hospital, Port_Hospital) %>%
head(10)# A tibble: 10 × 2
hospital Port_Hospital
<chr> <chr>
1 Other Não
2 Missing Não
3 St. Mark's Maternity Hospital (SMMH) Não
4 Port Hospital Sim
5 Military Hospital Não
6 Port Hospital Sim
7 Missing Não
8 Missing Não
9 Missing Não
10 Missing Não
dados_debola %>%
mutate(Fase = ifelse(age_years < 18, "Criança",
ifelse(age_years > 60, "Idoso", "Adulto"))) %>%
select(age_years, Fase ) %>%
head(10)# A tibble: 10 × 2
age_years Fase
<dbl> <chr>
1 2 Criança
2 3 Criança
3 56 Adulto
4 18 Adulto
5 3 Criança
6 16 Criança
7 16 Criança
8 0 Criança
9 61 Idoso
10 27 Adulto
dados_debola %>%
mutate(Faixa = cut(age_years, breaks=c(0, 20, 40, 60, 80, 100),
right=F) )%>%
select(age_years, Faixa ) %>%
head(10)# A tibble: 10 × 2
age_years Faixa
<dbl> <fct>
1 2 [0,20)
2 3 [0,20)
3 56 [40,60)
4 18 [0,20)
5 3 [0,20)
6 16 [0,20)
7 16 [0,20)
8 0 [0,20)
9 61 [60,80)
10 27 [20,40)
dados_debola %>%
mutate(Faixa = cut(age_years, breaks=c(0, 20, 40, 60, 80, 100),
labels= c("< 20 anos", "21-40 anos", "31-60 anos",
"61-80 anos", "> 80 anos"),
right=F) )%>%
select(age_years, Faixa ) %>%
head(10)# A tibble: 10 × 2
age_years Faixa
<dbl> <fct>
1 2 < 20 anos
2 3 < 20 anos
3 56 31-60 anos
4 18 < 20 anos
5 3 < 20 anos
6 16 < 20 anos
7 16 < 20 anos
8 0 < 20 anos
9 61 61-80 anos
10 27 21-40 anos
dados_debola %>%
mutate(idade_anos = case_when(
age_unit == "years" ~ age,
age_unit == "months" ~ age/12) ) %>%
select(age_unit, age, idade_anos) %>%
group_by(age_unit) %>%
sample_n(3)# A tibble: 6 × 3
# Groups: age_unit [2]
age_unit age idade_anos
<chr> <dbl> <dbl>
1 months 24 2
2 months 5 0.417
3 months 6 0.5
4 years 10 10
5 years 5 5
6 years 9 9
dados_debola %>%
mutate(Desfecho = case_when(
outcome == "Death" ~ "Óbito",
outcome == "Recover" ~ "Recuperado",
.default = "Investigar")) %>%
select(outcome, Desfecho) %>%
group_by(outcome) %>%
sample_n(3)# A tibble: 9 × 2
# Groups: outcome [3]
outcome Desfecho
<chr> <chr>
1 Death Óbito
2 Death Óbito
3 Death Óbito
4 Recover Recuperado
5 Recover Recuperado
6 Recover Recuperado
7 <NA> Investigar
8 <NA> Investigar
9 <NA> Investigar